<template>
  <div class="create-couple-container">
    <div class="create-couple-card">
      <div class="create-couple-header">
        <h1 class="create-couple-title">💕 创建情侣关系</h1>
        <p class="create-couple-subtitle">开启你们的甜蜜记账之旅</p>
      </div>

      <!-- 创建表单 -->
      <el-form 
        v-if="!inviteCode" 
        :model="createForm" 
        :rules="rules" 
        ref="createFormRef" 
        class="create-couple-form"
      >
        <el-form-item label="情侣昵称" prop="coupleName">
          <el-input
            v-model="createForm.coupleName"
            placeholder="给你们的关系起个可爱的名字吧"
            size="large"
            prefix-icon="Heart"
          />
        </el-form-item>

        <el-form-item label="恋爱开始日期" prop="loveDate">
          <el-date-picker
            v-model="createForm.loveDate"
            type="date"
            placeholder="选择你们在一起的日期"
            size="large"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="create-button"
            :loading="loading"
            @click="handleCreate"
          >
            创建情侣关系
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 邀请码展示 -->
      <div v-else class="invite-code-section">
        <div class="success-icon">✨</div>
        <h2 class="success-title">创建成功！</h2>
        <p class="success-subtitle">请将邀请码分享给你的TA</p>
        
        <div class="invite-code-box">
          <div class="invite-code">{{ inviteCode }}</div>
          <el-button 
            type="primary" 
            size="small" 
            @click="copyInviteCode"
            class="copy-button"
          >
            复制邀请码
          </el-button>
        </div>

        <div class="couple-info">
          <p><strong>情侣昵称：</strong>{{ coupleInfo.coupleName }}</p>
          <p><strong>恋爱日期：</strong>{{ coupleInfo.loveDate }}</p>
        </div>

        <el-button 
          type="success" 
          size="large" 
          class="go-home-button"
          @click="goHome"
        >
          返回首页
        </el-button>
      </div>

      <div class="create-couple-footer">
        <router-link to="/join-couple" class="link">已有邀请码？点击加入</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createCouple } from '@/api'

const router = useRouter()

const createFormRef = ref(null)
const loading = ref(false)
const inviteCode = ref('')
const coupleInfo = ref({})

const createForm = reactive({
  coupleName: '',
  loveDate: ''
})

const rules = {
  coupleName: [
    { required: true, message: '请输入情侣昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在2-20个字符之间', trigger: 'blur' }
  ],
  loveDate: [
    { required: true, message: '请选择恋爱开始日期', trigger: 'change' }
  ]
}

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

const handleCreate = async () => {
  if (!createFormRef.value) return

  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await createCouple(createForm)

        console.log('创建情侣关系响应：', res)
        console.log('邀请码：', res.data.inviteCode)

        inviteCode.value = res.data.inviteCode
        coupleInfo.value = {
          coupleName: res.data.coupleName,
          loveDate: res.data.loveDate
        }

        // 清除"没有情侣关系"提示的标志
        sessionStorage.removeItem('hasShownNoCoupleMessage')

        ElMessage.success('情侣关系创建成功！')
      } catch (error) {
        console.error('创建失败：', error)
      } finally {
        loading.value = false
      }
    }
  })
}

const copyInviteCode = () => {
  console.log('准备复制邀请码：', inviteCode.value)

  if (!inviteCode.value) {
    ElMessage.error('邀请码为空，无法复制')
    return
  }

  // 优先使用 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(inviteCode.value).then(() => {
      ElMessage.success('邀请码已复制到剪贴板 ✨')
    }).catch((err) => {
      console.error('Clipboard API 复制失败：', err)
      // 降级到传统方法
      fallbackCopy()
    })
  } else {
    // 浏览器不支持 Clipboard API，使用传统方法
    fallbackCopy()
  }
}

// 备用复制方法
const fallbackCopy = () => {
  try {
    const textArea = document.createElement('textarea')
    textArea.value = inviteCode.value
    textArea.style.position = 'fixed'
    textArea.style.top = '0'
    textArea.style.left = '0'
    textArea.style.opacity = '0'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    const successful = document.execCommand('copy')
    document.body.removeChild(textArea)

    if (successful) {
      ElMessage.success('邀请码已复制到剪贴板 ✨')
    } else {
      ElMessage.error('复制失败，请手动复制')
    }
  } catch (err) {
    console.error('备用复制方法失败：', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

const goHome = () => {
  router.push('/home')
}
</script>

<style scoped>
.create-couple-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 20px;
}

.create-couple-card {
  width: 100%;
  max-width: 500px;
  background: #fff;
  border-radius: 24px;
  padding: 40px;
  box-shadow: 0 8px 24px rgba(255, 154, 158, 0.3);
}

.create-couple-header {
  text-align: center;
  margin-bottom: 40px;
}

.create-couple-title {
  font-size: 36px;
  font-weight: bold;
  background: linear-gradient(90deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 10px;
}

.create-couple-subtitle {
  font-size: 14px;
  color: #999;
}

.create-couple-form {
  margin-top: 30px;
}

.create-button {
  width: 100%;
  background: linear-gradient(90deg, #ff9a9e 0%, #fecfef 100%);
  border: none;
  font-size: 16px;
  font-weight: bold;
}

.invite-code-section {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 64px;
  margin-bottom: 20px;
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.success-title {
  font-size: 28px;
  font-weight: bold;
  color: #ff9a9e;
  margin-bottom: 10px;
}

.success-subtitle {
  font-size: 14px;
  color: #999;
  margin-bottom: 30px;
}

.invite-code-box {
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 30px;
}

.invite-code {
  font-size: 48px;
  font-weight: bold;
  letter-spacing: 8px;
  color: #ff9a9e;
  margin-bottom: 20px;
  font-family: 'Courier New', monospace;
}

.copy-button {
  background: linear-gradient(90deg, #ff9a9e 0%, #fecfef 100%);
  border: none;
}

.couple-info {
  background: #f9f9f9;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  text-align: left;
}

.couple-info p {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
}

.go-home-button {
  width: 100%;
}

.create-couple-footer {
  text-align: center;
  margin-top: 20px;
}

.link {
  color: #ff9a9e;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
}

.link:hover {
  color: #ff8a8e;
  text-decoration: underline;
}

@media (max-width: 768px) {
  .create-couple-card {
    padding: 30px 20px;
  }

  .create-couple-title {
    font-size: 28px;
  }

  .invite-code {
    font-size: 36px;
    letter-spacing: 4px;
  }
}
</style>

